package com.itboye.sunsun.person.ui;

import java.util.Iterator;
import java.util.List;

import com.itboye.sunsun.MainActivity;
import com.itboye.sunsun.R;
import com.itboye.sunsun.adapter.LocationAdapter;
import com.itboye.sunsun.application.App;
import com.itboye.sunsun.beans.LocationBean;
import com.itboye.sunsun.beans.MyCollectBean.CollectGoodsBean;
import com.itboye.sunsun.constants.SPContants;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.custome.XListView.OnXScrollListener;
import com.itboye.sunsun.login.ui.RegistActivity;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.utils.DebugLog;
import com.itboye.sunsun.utils.SPUtils;
import com.itboye.sunsun.volley.CodeErrorException;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.LoadedFrom;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class ManageLocationActivity extends BaseActivity implements OnClickListener,IXListViewListener ,OnItemClickListener{

	private RelativeLayout backrela;
	private RelativeLayout addlocationrela;
	private XListView xlistview;
	private LocationAdapter adapter;
    private List<LocationBean> list;
	private View headerview;
	private LinearLayout linear;
	private String defaultid;
	
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		
	
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_managelocation);
		setStatusBarColor(R.color.top_blue);
		showProgressDialog("数据拉取中，请稍后", true);
		xlistview.setOnItemClickListener(this);
		xlistview.setXListViewListener(this);
		xlistview.setPullLoadEnable(false);
		xlistview.setPullRefreshEnable(true);
		getDefaultLocation();
		getAllLocation();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.backrela:
			this.finish();
			break;
		case R.id.addlocationrela:
			Intent intent = new Intent();
			intent.setClass(App.ctx, AddLocationActivity.class);
			intent.putExtra("from", "person");
			startActivity(intent);
			break;
		default:
			break;
		}

	}

	// 创建ListView布局
	public void createView(List<LocationBean> myList) {
		// this.list=myList;

		adapter = new LocationAdapter(App.ctx, myList);

		//LayoutInflater inflater = getLayoutInflater();

		//headerview = inflater.inflate(R.layout.location_listview_headerview, null, true);
		//xlistview.addHeaderView(headerview);

		// 从header中找到LinearLayot，这样隐藏掉View也不会占用空间
		//linear = (LinearLayout) headerview.findViewById(R.id.headlayout);

		//linear.setVisibility(View.GONE);
		xlistview.setAdapter(adapter);
		
		
	}

	// 获取默认地址ID
	public void getDefaultLocation() {

		// Toast.makeText(App.ctx, (String)SPUtils.get(App.ctx, null,
		// SPContants.USER_ID, ""), 0).show();
		MyJsonRequest<String> request = new MyJsonRequest.Builder<String>().apiVer("100")
				.typeKey("BY_Address_getDefaultAddress")
				.param("uid", (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, ""))

				.requestListener(new XRequestListener<String>() {

					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						DebugLog.v("result", response.toString());
						
						
						if(!response.toString().equals("0"))
						{
						   defaultid=response.toString();
						 // Toast.makeText(App.ctx, response.toString(), 0).show();
						}else
						{
							// Toast.makeText(App.ctx, response.toString(), 0).show();
						}
						//getSingleLocation(response.toString());
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						Toast.makeText(App.ctx, "网络异常", 0).show();
						if (exception instanceof CodeErrorException) {
							// Toast.makeText(App.ctx, msg, 0).show();
						} else {
							Toast.makeText(App.ctx, "网络异常", 0).show();
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	// 获取单个地址
	public void getSingleLocation(String response) {
		// Toast.makeText(App.ctx, (String)SPUtils.get(App.ctx, null,
		// SPContants.USER_ID, ""), 0).show();
		MyJsonRequest<LocationBean> request = new MyJsonRequest.Builder<LocationBean>().apiVer("100")
				.typeKey("BY_Address_getInfo").param("uid", (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, ""))
				.param("id", response)

				.requestListener(new XRequestListener<LocationBean>() {

					@Override
					public void onResponse(LocationBean response) {
						// TODO Auto-generated method stub
						DebugLog.v("result", response.toString());
						// Toast.makeText(App.ctx, response, 0).show();
						//Toast.makeText(App.ctx, response.getCity(), 0).show();
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						//Toast.makeText(App.ctx, code + "", 0).show();
						if (exception instanceof CodeErrorException) {
							// Toast.makeText(App.ctx, msg, 0).show();
						} else {
							Toast.makeText(App.ctx, "网络异常", 0).show();
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	// 获取全部地址
	public void getAllLocation() {
		MyJsonRequest<List<LocationBean>> request = new MyJsonRequest.Builder<List<LocationBean>>()
				.apiVer("100")
				.typeKey("BY_Address_queryNoPaging")
				.param("uid", (String) SPUtils.get(App.ctx, null, SPContants.USER_ID, ""))

				.requestListener(new XRequestListener<List<LocationBean>>() {

					@Override
					public void onResponse(List<LocationBean> myList) {
						// TODO Auto-generated method stub
						
						
//						Iterator<LocationBean> itor = myList.iterator();
//						while (itor.hasNext()) {
//							LocationBean bean = itor.next();
//							if (bean.getId().equals(defaultid)) {
//								itor.remove();
//								itor.
//							}
//						}

						
						//getDefaultLocation();
						//mAdapter.notifyDataSetChanged();
						DebugLog.v("defaultid", defaultid);
						//遍历全部地址，如果某个地址是默认地址，就将他放在集合的第一个
						for(int i=0;i<myList.size();i++)
						{
							if(myList.get(i).getId().equals(defaultid))
							{
								
								LocationBean defaultbean=myList.get(i);
								myList.remove(i);
								myList.add(0,defaultbean);
								
							}
							
						}
						
						
						list=myList;
						for(int i=0;i<myList.size();i++)
						{
							DebugLog.v("resultarea", myList.get(i).getArea() + "");
							
						}
						createView(myList);
try {
	closeProgressDialog();
} catch (Exception e) {
	// TODO: handle exception
}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code, String msg) {
						Toast.makeText(App.ctx, "网络异常", 0).show();
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}

					}
				}).build();
		HttpRequest.getDefaultRequestQueue().add(request);

	}
	
	
	
	//注册广播接收者
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		getAllLocation();
		
		IntentFilter filter=new IntentFilter(AddLocationActivity.CHANGEADDRESS);
		registerReceiver(mBroadcastReceiver, filter);
	}
	
	//解注册
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver);
	}

	@Override
	public void onRefresh() {
		xlistview.stopRefresh();
		
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		
	}

	
	//详细信息
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		Intent intent=new Intent(this,DetailLocationActivity.class);
		
		
		
		
		String province=list.get(position-1).getProvince();
		String city=list.get(position-1).getCity();
		String area=list.get(position-1).getArea();
		
		if(city.equals("市辖区")|city.equals("县"))
		{
			city="";
		}
		if(area.equals("市辖区"))
		{
			area="";
		}
		String wholelocation=province+city+area;
		
		
		String detail=list.get(position-1).getDetailinfo();
		String zipcode=list.get(position-1).getPostal_code();
		String name=list.get(position-1).getContactname();
		String phone=list.get(position-1).getMobile();
		String locationid=list.get(position-1).getId();
		
		
		intent.putExtra("id", 	locationid);
		intent.putExtra("wholelocation", wholelocation);
		intent.putExtra("detail", detail);
		intent.putExtra("zipcode", zipcode);
		intent.putExtra("name", name);
		intent.putExtra("phone", phone);
		startActivity(intent);
	}
	//广播接收者
	BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			
			getDefaultLocation();
			getAllLocation();
			adapter.notifyDataSetChanged();
			
		};
	};





}
